package com.jwdf.uda.fileupload.listener.impl;

import android.os.Handler;
import android.os.Message;

import com.jwdf.uda.fileupload.bean.ProgressObj;
import com.jwdf.uda.fileupload.handler.ProgressUIHandler;
import com.jwdf.uda.fileupload.listener.ProgressListener;

/**
 * Created by Administrator on 2016/7/27.
 */
public abstract class UploadProgressListener implements ProgressListener{
    private boolean isFirst = false;

    private static class UIHandler extends ProgressUIHandler {
        public UIHandler(UploadProgressListener listener) {
            super(listener);
        }

        @Override
        public void onStart(UploadProgressListener listener) {
            if (listener!=null) {
                listener.onStartUpload();
            }
        }

        @Override
        public void onProgress(UploadProgressListener listener, long currentBytes, long contentLength) {
            if (listener!=null){
                listener.onUpdateProgress(currentBytes, contentLength);
            }
        }

        @Override
        public void onFinish(UploadProgressListener listener) {
            if (listener!=null){
                listener.onFinishUpload();
            }
        }
    }

    private final Handler mHandler = new UIHandler(this);

    @Override
    public void onProgress(long bytesWrite, long contentLength, boolean done) {
        if (!isFirst) {
            isFirst = true;
            Message start = Message.obtain();
            start.obj = new ProgressObj(bytesWrite, contentLength, done);
            start.what = ProgressUIHandler.START;
            mHandler.sendMessage(start);
        }

        Message message = Message.obtain();
        message.obj = new ProgressObj(bytesWrite, contentLength, done);
        message.what = ProgressUIHandler.UPDATE;
        mHandler.sendMessage(message);

        if(done) {
            Message finish = Message.obtain();
            finish.obj = new ProgressObj(bytesWrite, contentLength, done);
            finish.what = ProgressUIHandler.FINISH;
            mHandler.sendMessage(finish);
        }
    }

    public abstract void onUpdateProgress(long currentBytes, long contentLength);//(int) ((100 * bytesWrite) / contentLength)

    public void onStartUpload() {

    }

    public void onFinishUpload() {

    }
}
